package com.lzy.cloud.search.client.service.impl;

import com.lzy.cloud.search.client.entity.EsIndex;
import com.lzy.cloud.search.client.entity.EsQuery;
import com.lzy.cloud.search.client.service.GetDocmentService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 获取文档信息
 */
@Service
public class GetDocmentServiceImpl  implements GetDocmentService {

    @Autowired
    private EsClient client;


    /**
     * 根据id查看文档
     */
    @Override
    public GetResponse getDocment(EsIndex esIndex)   {
        GetResponse response = client.getConnection().prepareGet(esIndex.getName(), esIndex.getType(),esIndex.getId() ).get();

//        GetResponse response = client.prepareGet("twitter", "tweet", "1")
//                .setOperationThreaded(false)  //`true` 是在不同的线程里执行此次操作
//                .get();
        if (response.isExists()) {
            System.out.println("GetApi 有此文档：" + response.toString());
        } else {
            System.out.println("GetApi 没有此文档：" + response.toString());
        }
        return response;
    }

    /**
     * 一次性获取多个文档
     * @ 
    */
    @Override
    public MultiGetResponse multiGet(List<EsIndex> esIndexList)   {
        MultiGetRequestBuilder multiGetRequestBuilder = client.getConnection().prepareMultiGet();

        for (EsIndex esIndex : esIndexList) {
            multiGetRequestBuilder.add(esIndex.getName(),esIndex.getType(),esIndex.getIds());

        }
        

//        for (MultiGetItemResponse itemResponse : multiGetItemResponses) { //迭代返回值
//            GetResponse response = itemResponse.getResponse();
//            if (response != null && response.isExists()) {      //判断是否存在
//                String json = response.getSourceAsString(); //_source 字段
//                System.out.println("_source 字段:" + json);
//            }
//        }
        return multiGetRequestBuilder.get();
    }

}
